package top.luo.mycat.server;


import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.Node;
import org.dom4j.io.SAXReader;

import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * mycat 启动类
 *
 * @author luo
 * @date 2021-03-16 21:20
 */
public class Bootstrap {

    private final Map<String, HttpServlet> servletMap = new HashMap<>();

    public static final int PORT = 8080;

    public static void main(String[] args) {
        Bootstrap bootstrap = new Bootstrap();
        bootstrap.startupV5();
    }

    /**
     * v1 简单实现
     *
     * <p> 最主要的操作，开启监听
     */
    public void startupV1() {
        try (ServerSocket serverSocket = new ServerSocket(PORT)) {
            System.out.println("mycat start on port: " + PORT);

            while (true) {
                Socket socket = serverSocket.accept();

                // 接收到请求
                OutputStream ous = socket.getOutputStream();
                String res = "hello mycat";
                String header = HttpProtocolUtils.getHttpHeaderOk(res.getBytes().length);
                ous.write((header + res).getBytes());

                socket.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * v2 封装Request，Response， 请求静态资源 html
     *
     * <p> 最主要的操作，开启监听
     */
    public void startupV2() {
        try (ServerSocket serverSocket = new ServerSocket(PORT)) {
            System.out.println("mycat start on port: " + PORT);

            while (true) {
                Socket socket = serverSocket.accept();
                // 获取输入
                InputStream ins = socket.getInputStream();

                // 封装request response 对象
                Request request = new Request(ins);
                Response response = new Response(socket.getOutputStream());

                // 输出 html 文件
                response.outputHtml(request.getUrl());

                socket.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * v3 可以请求动态资源 servlet
     *
     * <p> 最主要的操作，开启监听
     */
    public void startupV3() {
        // 解析配置文件 web.xml
        loadServlet();

        try (ServerSocket serverSocket = new ServerSocket(PORT)) {
            System.out.println("mycat start on port: " + PORT);

            while (true) {
                Socket socket = serverSocket.accept();
                // 获取输入
                InputStream ins = socket.getInputStream();

                // 封装request response 对象
                Request request = new Request(ins);
                Response response = new Response(socket.getOutputStream());

                /* 判断是静态资源还是静态资源 */
                // 动态资源
                if (servletMap.containsKey(request.getUrl())) {
                    HttpServlet httpServlet = servletMap.get(request.getUrl());
                    httpServlet.service(request, response);
                }
                // 静态资源
                else {
                    // 输出 html 文件
                    response.outputHtml(request.getUrl());
                }

                socket.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * v4 使用线程处理每个请求
     *
     * <p> 最主要的操作，开启监听
     */
    public void startupV4() {
        // 解析配置文件 web.xml
        loadServlet();

        try (ServerSocket serverSocket = new ServerSocket(PORT)) {
            System.out.println("mycat start on port: " + PORT);

            while (true) {
                Socket socket = serverSocket.accept();

                RequestProcessor requestProcessor = new RequestProcessor(socket, servletMap);
                requestProcessor.start();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * v5 线程池
     *
     * <p> 最主要的操作，开启监听
     */
    public void startupV5() {
        // 解析配置文件 web.xml
        loadServlet();

        // 定义一个线程池
        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(
                Runtime.getRuntime().availableProcessors() / 4,
                Runtime.getRuntime().availableProcessors(),
                60L,
                TimeUnit.SECONDS,
                new ArrayBlockingQueue<>(Runtime.getRuntime().availableProcessors() * 2),
                Executors.defaultThreadFactory(),
                new ThreadPoolExecutor.AbortPolicy()
        );


        try (ServerSocket serverSocket = new ServerSocket(PORT)) {
            System.out.println("mycat start on port: " + PORT);

            while (true) {
                Socket socket = serverSocket.accept();

                RequestProcessor requestProcessor = new RequestProcessor(socket, servletMap);
                threadPoolExecutor.execute(requestProcessor);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 加载配置文件， 初始化servlet
     */
    private void loadServlet() {
        InputStream ins = this.getClass().getResourceAsStream("/web.xml");
        SAXReader saxReader = new SAXReader();
        try {
            Document document = saxReader.read(ins);
            Element root = document.getRootElement();

            List<Element> servletNodes = root.selectNodes("//servlet");
            for (Element element : servletNodes) {
                Node servletNameNode = element.selectSingleNode("servlet-name");
                String servletName = servletNameNode.getStringValue();

                Node servletClassNode = element.selectSingleNode("servlet-class");
                String servletClass = servletClassNode.getStringValue();

                // 根据 servlet-name 找到 url-pattern
                Node mappingNode = root.selectSingleNode("/web-app/servlet-mapping[servlet-name='" + servletName + "']");
                String urlPattern = mappingNode.selectSingleNode("url-pattern").getStringValue();

                servletMap.put(urlPattern, (HttpServlet) Class.forName(servletClass).newInstance());
            }


        } catch (DocumentException | ClassNotFoundException | IllegalAccessException | InstantiationException e) {
            e.printStackTrace();
        }
    }

}
